package com.iaiai.notepad;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.iaiai.notepad.util.DateUtil;

/**
 * 
 * <p>
 * Title: FileActivity.java
 * </p>
 * <p>
 * E-Mail: 176291935@qq.com
 * </p>
 * <p>
 * QQ: 176291935
 * </p>
 * <p>
 * Http: iaiai.iteye.com
 * </p>
 * <p>
 * Create time: 2011-12-4
 * </p>
 * 
 * @author 丸子
 * @version 0.0.1
 */
public class FolderActivity extends Activity {

	private Button btnTop;

	private Button btnReturn;

	private Button btnSave;

	private ListView listView;

	private FileAdapter adapter;

	private TextView urlAddress;

	private String url = "/"; // 当前地址

	private ProgressDialog loadingDialog; // loading

	private void init() {
		loadingDialog = new ProgressDialog(this);
		loadingDialog.setMessage("Loading...");
		loadingDialog.setCancelable(false);

		btnTop = (Button) findViewById(R.id.btnTop);
		btnReturn = (Button) findViewById(R.id.btnReturn);
		btnSave = (Button) findViewById(R.id.btnSave);
		listView = (ListView) findViewById(R.id.listView);
		urlAddress = (TextView) findViewById(R.id.urlAddress);

		btnTop.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (!url.equals("/")) {
					String temp = url.substring(0, url.lastIndexOf("/"));
					temp = temp.substring(0, temp.lastIndexOf("/"));
					final String address = temp.length() <= 0 ? "/" : temp;
					loadingDialog.show();

					final Handler handler = new Handler();
					new Thread() {
						public void run() {
							handler.post(new Runnable() {
								public void run() {
									updateAddress(address);
									loadingDialog.cancel();
								}
							});
						}
					}.start();
				}
			}
		});
		btnReturn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		btnSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (!sdCardIsExsit()) {
					Toast.makeText(FolderActivity.this, "sdcard不存在或有写保护!",
							Toast.LENGTH_LONG).show();
					return;
				}

				String filename = url.replace("//", "");
				// 判断如果不是在sdcard上不能保存
				if (!filename.toLowerCase().startsWith("/sdcard")
						&& !filename.toLowerCase().startsWith("/mnt/sdcard")) {
					Toast.makeText(FolderActivity.this,
							"此文件不能编辑，只能编辑sdcard上的文件!", Toast.LENGTH_LONG)
							.show();
					return;
				}

				save(); // 保存
			}
		});

		urlAddress.setText(url == null ? "/" : url);
		// 配置适配器
		adapter = new FileAdapter(FolderActivity.this, getData(url));

		// 添加并且显示
		listView.setAdapter(adapter);

		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				final Map<String, Object> map = (Map<String, Object>) adapter
						.getItem(position);
				if (!Boolean.parseBoolean(map.get("type").toString())) { // 不是文件
					loadingDialog.show();

					final Handler handler = new Handler();
					new Thread() {
						public void run() {
							handler.post(new Runnable() {
								public void run() {
									updateAddress(url
											+ map.get("filename").toString());
									loadingDialog.cancel();
								}
							});
						}
					}.start();
				}
			}
		});
	}

	private void save() {
		Bundle bundle = getIntent().getExtras();
		String filename = url + bundle.getString("filename");
		final String content = bundle.getString("content");

		final File file = new File(filename);
		if (!file.exists()) {
			if (saveFile(content, file)) {
				Toast.makeText(FolderActivity.this, "保存成功!", Toast.LENGTH_LONG)
						.show();
				finish();
			}
		} else {
			new AlertDialog.Builder(this)
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									if (saveFile(content, file)) {
										Toast.makeText(FolderActivity.this,
												"保存成功!", Toast.LENGTH_LONG)
												.show();
										finish();
									}
								}
							}).setNegativeButton(android.R.string.cancel, null)
					.setIcon(R.drawable.icon).setTitle("提示")
					.setMessage("有此文件，是否覆盖？").show();
		}
	}

	private boolean saveFile(String content, File file) {
		try {
			byte[] b = content.getBytes();
			OutputStream out = new FileOutputStream(file);
			for (byte temp : b) {
				out.write(temp);
			}
			out.close();
		} catch (FileNotFoundException e) {
			Toast.makeText(FolderActivity.this, "sdcard不存在或有写保护!",
					Toast.LENGTH_LONG).show();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * 更新地址
	 * 
	 * @param filename
	 */
	private void updateAddress(String filename) {
		urlAddress.setText(filename);

		adapter.setData(getData(filename));
		url = filename + "/";
		adapter.notifyDataSetChanged();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.folder);

		init();
	}

	/**
	 * 获得数据
	 * 
	 * @return
	 */
	private List<Map<String, Object>> getData(String address) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		File root = new File(address);
		File[] files = root.listFiles();
		if (files != null) {
			for (File file : files) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("filename", file.getName());
				map.put("date",
						DateUtil.getDateTime(new Date(file.lastModified())));
				map.put("size", file.length());
				map.put("type", file.isFile()); // 存储是否是文件，true是，false不是

				list.add(map);
			}
		}
		return list;
	}

	/**
	 * 判断sdcard是否已安装
	 * 
	 * @return true安装，false未安装
	 */
	private boolean sdCardIsExsit() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

}
